﻿//========================================================================
// *作者：海盗猫  主页：ilplay.com
// *脚本：UIEntityBase
// *描述：UIEntityBase
// *?2024 HDMCode . All rights reserved.
//* ======================================================================

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace HDMCode.UIFrame
{
    public class UIEntityBase
    {
        /// <summary>
        /// 当前UI名称
        /// </summary>
        public string UIName;
        
        /// <summary>
        /// 当前UI是否正在显示
        /// </summary>
        public bool IsShow;

        /// <summary>
        /// 是否时首次显示
        /// </summary>
        protected bool isFrist=true;
        
        /// <summary>
        /// 当前UI映射的组件
        /// </summary>
        internal IUIFrameComponent UIFrameComponent;
        
        /// <summary>
        /// 当前控制
        /// </summary>
        internal UIDisplay UIDisplay;
        
        /// <summary>
        /// 动画组件
        /// </summary>
        protected Animator m_Animator;

        /// <summary>
        /// 音频组件
        /// </summary>
        protected AudioSource m_AudioSource;

        /// <summary>
        /// UI行为监听事件管理
        /// </summary>
        protected IUIDisplayEvent m_UiEvent { get; set; } = new UIDisplayEvent();

        /// <summary>
        /// 当前添加的克隆UI
        /// </summary>
        protected List<UIDisplay> m_TampCloneUIs = new();
        
        /// <summary>
        /// 检查Animator组件
        /// </summary>
        protected void CheckAnimator()
        {
            if (UIDisplay.animation)
            {
                if (UIDisplay.TryGetComponent<Animator>(out var animator))
                    m_Animator = animator;
                else
                {
                    m_Animator = UIDisplay.gameObject.AddComponent<Animator>();
                    m_Animator.runtimeAnimatorController = UIDisplay?.animation;
                }
            }
        }

        /// <summary>
        /// 检查播放组件
        /// </summary>
        protected void CheckAudio()
        {
            if (UIDisplay.openAudio || UIDisplay.closeAudio)
            {
                if (UIDisplay.TryGetComponent<AudioSource>(out var audio))
                    m_AudioSource = audio;
                else
                    m_AudioSource = UIDisplay.gameObject.AddComponent<AudioSource>();
            }
        }

        /// <summary>
        /// 延时回调事件，给一个固定事件是为了避免不满足条件时，导致监听没成功
        /// </summary>
        /// <param name="time">需要延时的事件</param>
        /// <returns></returns>
        public UIEntityEvent AsyncEvent(float time)
        {
            if (time <= 0.01f)
                time = 0.01f;
            UIEntityEvent events = new UIEntityEvent();
            HDMUI.Helper.AsyncUIAwait(time, () =>
            {
                events.onComplete?.Invoke();
            });
            return events;
        }
    }
}
